const http = require('http');
const proxy = require('http-proxy').createProxy();
const url = require('url');

let map = {
  'a.ahhh.cn:8081'/*这个8081是和下面.listen的对口号绑定的*/: 'http://localhost:3000'
  ,'b.ahhh.cn:8081': 'http://localhost:4000'
};


http.createServer((req, res) => {
  console.log(req.headers.host); // a.ahhh.cn:8081 //req.headers.host获取的host是带端口号的 url.parse解析出的hostname是不带端口号的
  /*proxy.web(req,res,{
    target: map[req.headers.host]
  })*/
  web(req,res,{
    target: map[req.headers.host]
  })
}).listen(8081);

//大概实现思路↓
function web(req,res,options){
  console.log('req.headers:',req.headers)
  const {path} = url.parse(req.url);
  const [hostname, port] = options.target.slice(7).split(':');
  const request_headers = {};
  delete req.headers.host; //貌似不用删除也可以
  Object.keys(req.headers).forEach(item => {
    const key = item.split('-').map(item => item.charAt(0).toUpperCase() + item.slice(1)).join('-');
    console.log('key:',key);
    request_headers[key] = req.headers[item];
  });
  console.log('request_headers:',request_headers);
  let opts = {
    hostname //hostname是host的别名 主要为了支持url.parse
    ,port
    ,method:req.method
    ,path //包括查询字符串
    ,headers:request_headers //貌似首字母小写也可以 req.headers
  };
  console.log('opts:',opts);

  console.log('------正在代理-----');
  let x = http.request(opts, (response) => {
    // console.log(response);
    response.writeHead(res.statusCode, res.headers);
    console.log('------正在返回-----');
    response.pipe(res);
  });
  x.on('error', (err) => {
    console.log('代理错误:',err);
  });
  x.end();
}


/*
const url = require('url');
const x = 'http://b.ahhh.cn:3000/index.html'

console.log(url.parse(x));
/!*
Url {
  protocol: 'http:',
    slashes: true,
    auth: null,
    host: 'b.ahhh.cn:3000',
    port: '3000',
    hostname: 'b.ahhh.cn',
    hash: null,
    search: null,
    query: null,
    pathname: '/index.html', //不包括查询字符串
    path: '/index.html', //包括查询字符串
    href: 'http://b.ahhh.cn:3000/index.html' }*!/*/
